﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using System.Text;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Sys_ModuleController : Controller
    {

        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        public string GetGridInfo()
        {
            return @" {'action':true,'message':'error!',
  'data':[
  {'number':'1','text1': '3','info1': '4','special1': '5'},
{'number':'2','text1': '3','info1': '4','special1': '<input type=\'checkbox\' value=\'xx权限\' class=\'abc123\' />xx权限&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   <input type=\'checkbox\' value=\'xx权限\' class=\'abc123\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />'},
{'number':'3','text1': '3','info1': '4','special1': '<input type=\'checkbox\' value=\'xx权限\' class=\'abc123\' />xx权限&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   <input type=\'checkbox\' value=\'xx权限\' class=\'abc123\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />xx权限    <input type=\'checkbox\' value=\'xx权限\' />'},
{'number':'4','text1': '3','info1': '4','special1': '5'}
  ],
  'columModle':[
  {'header': '序号','dataIndex': 'number','width':40},
  {'header': '编码','dataIndex': 'text1', editor: {
                    xtype: 'checkbox',
                    cls: 'x-grid-checkheader-editor'
                }},
  {'header': '名称','dataIndex': 'info1', editor: {
                    xtype: 'checkbox',
                    cls: 'x-grid-checkheader-editor'
                }},
  {'header': '金额','dataIndex': 'special1','width':300}
  ],
  'fieldsNames':[{name:'number'},{name:'text1'},{name:'info1'},{name:'special1'}]
  }";
        }

        /// <summary>
        /// 返回功能模块列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            int recordNum = 0;
            QueryParam qp = new QueryParam();
            qp.Orderfld = "M_OrderLevel desc ";
            //返回json数组
            if (!string.IsNullOrEmpty(actionId) && actionId.StartsWith("m"))
            {
                qp.PageIndex = 1;
                qp.PageSize = int.MaxValue;
                
                IDataService<Sys_ModuleEntity> Sys_ModuleSv = ServiceBuilder.BuildSys_ModuleService();
                List<Sys_ModuleEntity> sys_moduleList = Sys_ModuleSv.List(qp, out recordNum);
                StringBuilder sb=new StringBuilder();
                sb.Append("[");
                GetTreeString(sb, 0, sys_moduleList);
                sb.Append("]");
                returnJson = sb.ToString(); 
                
            }
            else
            {
                int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
                int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
                int parentId = Utils.StringToInt(actionId,0);
                qp.PageIndex = pageIndex / pageSize + 1;
                qp.PageSize = pageSize;
                qp.Where = string.Concat(" M_ParentID=", parentId);
                IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
                IDataService<Sys_ModuleEntity> Sys_ModuleSv = ServiceBuilder.BuildSys_ModuleService();
                List<Sys_ModuleEntity> sys_moduleList = Sys_ModuleSv.List(qp, out recordNum);
                returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(sys_moduleList, Formatting.Indented, jsDataConvert), "}");
            }
            return returnJson;

        }
        /// <summary>
        /// 获取树状json 列表
        /// </summary>
        /// <param name="sb">记录容器</param>
        /// <param name="id">起始id</param>
        /// <param name="list">要循环的列表</param>
        protected void GetTreeString(StringBuilder sb, int id, List<Sys_ModuleEntity> list)
        {
            
            bool isHasChild = false;
            
            int intCount = 0;
            int intIndex = 0;
            foreach (Sys_ModuleEntity module in list)
            {

                //        {text:'系统管理',url:'',name2:'tree1',id:'tree1',expanded:true,children:[
                //{text:'功能模块',url:'/Sys_Module/Index',name2:'Sys_Module',id:'Sys_Module',leaf:true},
                //{text:'模块扩展权限',url:'/Sys_ModuleExtPermission/Index',id:'Sys_ModuleExtPermission',name2:'Sys_ModuleExtPermission',children:[
                //    {text:'01-02-01',url:'/Home/TreeList/',name2:'tree1',id:'tree4',leaf:true},
                //    {text:'01-02-02',url:'/Sys_Roles/Index',name2:'tree1',id:'tree5',leaf:true}
                //]},
                if (module.M_ParentID == id)
                {
                    intCount++;
                }


            }

            if (intCount != 0)
            {
                foreach (Sys_ModuleEntity module in list)
                {

                    //        {text:'系统管理',url:'',name2:'tree1',id:'tree1',expanded:true,children:[
                    //{text:'功能模块',url:'/Sys_Module/Index',name2:'Sys_Module',id:'Sys_Module',leaf:true},
                    //{text:'模块扩展权限',url:'/Sys_ModuleExtPermission/Index',id:'Sys_ModuleExtPermission',name2:'Sys_ModuleExtPermission',children:[
                    //    {text:'01-02-01',url:'/Home/TreeList/',name2:'tree1',id:'tree4',leaf:true},
                    //    {text:'01-02-02',url:'/Sys_Roles/Index',name2:'tree1',id:'tree5',leaf:true}
                    //]},
                    isHasChild = false;
                    if (module.M_ParentID == id)
                    {
                        intIndex++;

                        sb.Append(string.Concat("{text:'", module.M_CName, "',id:'", module.ModuleID, "'"));

                        foreach (Sys_ModuleEntity module2 in list)
                        {
                            if (module2.M_ParentID == module.ModuleID)
                            {
                                isHasChild = true;
                                sb.Append(",expanded:true,children:[");
                                break;
                            }
                        }
                        GetTreeString(sb, module.ModuleID, list);

                        if (isHasChild)
                        {
                            if (intIndex != intCount)
                            {

                                sb.Append("]},");
                            }
                            else
                            {
                                sb.Append("]}");
                            }
                        }
                        else
                        {
                            if (intIndex != intCount)
                            {
                                sb.Append(",leaf:true},");
                            }
                            else
                            {
                                sb.Append(",leaf:true}");
                            }
                        }
                    }

                }
            }

           
            

        }

        /// <summary>
        /// 查看功能模块 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
            IDataService<Sys_ModuleEntity> Sys_ModuleSv = ServiceBuilder.BuildSys_ModuleService();
            int intId = Utils.StringToInt(actionId,0);
            Sys_ModuleEntity sys_module = Sys_ModuleSv.Look(intId);
            if (sys_module != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(sys_module), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 更新功能模块
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Sys_ModuleEntity sys_module = new Sys_ModuleEntity();
                sys_module.DataTable_Action = DataTableAction.Update;
                sys_module.ModuleID = intId;
                sys_module.M_ParentID = (Int32)Utils.GetQueryAndFormString("M_ParentID", this, 10, 1, DataType.Int);
                sys_module.M_PageCode = (String)Utils.GetQueryAndFormString("M_PageCode", this, 6, 1, DataType.Str);
                sys_module.M_CName = (String)Utils.GetQueryAndFormString("M_CName", this, 50, 0, DataType.Str);
                sys_module.M_Directory = (String)Utils.GetQueryAndFormString("M_Directory", this, 255, 0, DataType.Str);
                sys_module.M_OrderLevel = (String)Utils.GetQueryAndFormString("M_OrderLevel", this, 4, 0, DataType.Str);
                sys_module.M_IsSystem = (Byte)Utils.GetQueryAndFormString("M_IsSystem", this, 3, 0, DataType.Byte);
                sys_module.M_Close = (Byte)Utils.GetQueryAndFormString("M_Close", this, 3, 0, DataType.Byte);
                sys_module.M_Icon = (String)Utils.GetQueryAndFormString("M_Icon", this, 255, 0, DataType.Str);
                IDataService<Sys_ModuleEntity> Sys_ModuleSv = ServiceBuilder.BuildSys_ModuleService();
                if (Sys_ModuleSv.Update(sys_module) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }

            return returnJson;
        }

        /// <summary>
        /// 新增功能模块
        /// </summary>
        /// <returns>json</returns>
        public string Insert()
        {
            Sys_ModuleEntity sys_module = new Sys_ModuleEntity();
            sys_module.DataTable_Action = DataTableAction.Insert;
            sys_module.M_ParentID = (Int32)Utils.GetQueryAndFormString("M_ParentID", this, 10, 1, DataType.Int);
            sys_module.M_PageCode = (String)Utils.GetQueryAndFormString("M_PageCode", this, 6, 1, DataType.Str);
            sys_module.M_CName = (String)Utils.GetQueryAndFormString("M_CName", this, 50, 0, DataType.Str);
            sys_module.M_Directory = (String)Utils.GetQueryAndFormString("M_Directory", this, 255, 0, DataType.Str);
            sys_module.M_OrderLevel = (String)Utils.GetQueryAndFormString("M_OrderLevel", this, 4, 0, DataType.Str);
            sys_module.M_IsSystem = (Byte)Utils.GetQueryAndFormString("M_IsSystem", this, 3, 0, DataType.Byte);
            sys_module.M_Close = (Byte)Utils.GetQueryAndFormString("M_Close", this, 3, 0, DataType.Byte);
            sys_module.M_Icon = (String)Utils.GetQueryAndFormString("M_Icon", this, 255, 0, DataType.Str);
            ISearchDataService<Sys_ModuleEntity> Sys_ModuleSv = (ISearchDataService<Sys_ModuleEntity>) ServiceBuilder.BuildSys_ModuleService();
            if (Sys_ModuleSv.IsHas(sys_module.M_PageCode)>0)
            {
                returnJson = "{success:'false',message:'已存在的模块编码'}";
            }
            else
            {
                if (Sys_ModuleSv.Insert(sys_module) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 删除功能模块
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Sys_ModuleEntity sys_module = new Sys_ModuleEntity();
                sys_module.ModuleID = intId;
                IDataService<Sys_ModuleEntity> Sys_ModuleSv = ServiceBuilder.BuildSys_ModuleService();
                QueryParam qp = new QueryParam();
                qp.PageSize = 1;
                qp.Where = string.Concat("M_ParentID=", intId.ToString());
                int recordNum = 0;
                if (Sys_ModuleSv.List(qp, out recordNum).Count < 1)
                {
                    if (Sys_ModuleSv.Delete(sys_module) == "")
                    {
                        returnJson = "{success:'true'}";
                    }
                    else
                        returnJson = "{success:'false'}";
                }
                else
                {
                    returnJson = "{success:'false',message:'请先删除子模块'}";
                }
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除功能模块
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Sys_ModuleEntity> Sys_ModuleSv = ServiceBuilder.BuildSys_ModuleService();
                if (Sys_ModuleSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
